<template>
  <div class="page-container">
    <!-- 提示弹窗 -->
    <el-dialog v-model="infoVisible" title="提示" class="info_dialog">
      <h5>{{ info }}</h5>
    </el-dialog>

    <div class="main-body">
      <div class="sidebar">
        <!-- Tabs -->
        <div class="tabs">
          <div class="tab_title" :class="{ active: view === 3 }">个人中心</div>
          <div class="tab_item" :class="{ active: view === 0 }" @click="view = 0">我的信息</div>
          <div class="tab_item" :class="{ active: view === 1 }" @click="view = 1">我的头像</div>
          <div class="tab_item" :class="{ active: view === 2 }" @click="view = 2">账号安全</div>
          <div class="tab_item logout" @click="exitLogin">退出登录</div>
        </div>
      </div>

      <div class="content">
        <div v-if="view === 0" class="info-section">
          <h2>我的信息</h2>
          <el-form label-width="100px" class="user-info-form">
            <el-form-item label="昵称">
              <el-input v-model:readonly="isReadonly" type="text" v-model="userInfo.user_name" maxlength="30"
                show-word-limit />
            </el-form-item>
            <el-form-item label="性别">
              <el-select v-model:disabled="isReadonly" v-model="userInfo.gender" class="m-2" size="small"
                style="width: 256px;">
                <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="出生日期">
              <el-date-picker 
                v-model:readonly="isReadonly" 
                v-model="userInfo.birthday" 
                type="date"
                :default-value="new Date(2010, 9, 1)"
                style="width: 256px" />
            </el-form-item>
            
            <el-form-item label="个性签名">
              <el-input v-model:readonly="isReadonly" type="textarea" v-model="userInfo.bio" maxlength="100"
                show-word-limit resize="none" :autosize="{ minRows: 2, maxRows: 4 }" style="width: 100%" />
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="isReadonly = false" v-if="isReadonly">编辑</el-button>
          <div v-else>
            <el-button type="primary" @click="cancelEdit" class="btn-cancel">撤回</el-button>
            <el-button type="primary" @click="editUserInfo" class="btn-save">保存</el-button>
          </div>
        </div>

        <!-- 我的头像修改 -->
        <div v-else-if="view === 1" class="avatar-section">
          <h2>头像与背景修改</h2>
          <div class="upload-area">
            <el-upload class="avatar-uploader" :show-file-list="false" :before-upload="(file:File) => ImgUpload(file,  'avatar')">
              <el-avatar  fit="cover" :src="userInfo.avatar" class="avatar" style="width: 220px; height: 220px;" />
              <div class="overlay">
                <span class="text">头像更换</span>
              </div>

            </el-upload>
            <el-upload class="avatar-uploader" :show-file-list="false" :before-upload=" (file:File) => ImgUpload(file,  'bgcover')">
              <ElImage fit="contain" :src="userInfo.bgcover" class="avatar" style="height: 220px;" />
              <div class="overlay">
                <span class="text">背景更换</span>
              </div>

            </el-upload>
          </div>
        </div>

        <!-- 账号安全 -->
        <div v-else-if="view === 2" class="security-section">
          <div class="security-section">
            <h2>账号安全</h2>

            <!-- 修改密码 -->
            <div>
              <a href="#" @click.prevent="showDialog('password')">
                <el-button type="primary" class="btn-edit">修改密码</el-button>
              </a>
              <el-dialog title="修改密码" v-model="dialogVisible_pw">
                <div class="form">
                  <el-form label-width="100px" ref="form">
                    <el-form-item label="密码：" prop="password">
                      <el-input type="password" v-model="PWform.password" maxlength="30" minlength="6" show-word-limit
                        placeholder="请输入密码" />
                    </el-form-item>
                    <el-form-item label="确认密码：" prop="confirmPassword">
                      <el-input type="password" v-model="PWform.confirmPassword" maxlength="30" minlength="6"
                        show-word-limit placeholder="请确认密码" />
                    </el-form-item>

                    <!-- 检查密码长度是否符合要求 -->
                    <div v-if="PWform.password.length < 6" style="color: red;">
                      密码长度需大于6个字符！
                    </div>

                    <!-- 检查密码和确认密码是否匹配 -->
                    <div v-if="PWform.password !== PWform.confirmPassword" style="color: red;">
                      两次密码不一致！
                    </div>
                    <div style="margin-left: 4%;">
                      <span style="padding-right: 12px;">验证码：</span>
                      <el-input placeholder="输入验证码" v-model="pwCode" style="display: inline-block; width: 200px;" />
                      <el-button class="send-b" type="primary" :disabled="isDisabledOfPw" @click="sendCode('password')"
                        style="margin-left: 10px;">
                        {{ buttonTextOfPw }}
                      </el-button>
                    </div>
                    <br/>
                    <el-form-item>
                      <el-button class="exit-b" type="primary" @click="exitUpdatePassword"
                        style="background-color: #94213c; color: white;">
                        撤回
                      </el-button>

                      <!-- 确认按钮启用条件：密码长度、确认密码匹配、验证码成功 -->
                      <el-button class="send-b" type="primary"
                        :disabled="!(PWform.password === PWform.confirmPassword && PWform.password.length >= 6 && pwCodeSuccess)"
                        @click="updatePassword">
                        保存
                      </el-button>
                    </el-form-item>
                  </el-form>
                </div>
              </el-dialog>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>





<script setup lang="ts">
import { reactive, ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';
import { md5 } from 'js-md5';
import { useUserStore } from "@/stores/user";
import { ElImage, ElMessage } from 'element-plus';

const user = useUserStore();
const my_id = user.loginstatus ? user.userInfo.id : -1;
const view = ref(0);
const info = ref("");
const title = ref("");
const infoVisible = ref(false);

const userInfo = reactive({
  user_name: "",
  bio: "",
  birthday: "",
  gender: "无性别",
  mobile: "",
  avatar: "",
  bgcover: "",
  phone: ""
});

const cache = { ...userInfo };
const isReadonly = ref(true);
const phoneNumber = ref("");
const newPhone = ref("");
const phoneCode = ref("");
const pwCode = ref("");
const dialogVisible_phone = ref(false);
const dialogVisible_pw = ref(false);
const phoneCodeSuccess = ref(false);
const pwCodeSuccess = ref(false);
const isDisabledOfPhoneNumber = ref(false);
const buttonTextOfPhoneNumber = ref('发送验证码');
const isDisabledOfPw = ref(false);
const buttonTextOfPw = ref('发送验证码');



// 打开密码修改弹窗
const showDialog = (type) => {
  if (type === 'password') {
    dialogVisible_pw.value = true;
  }
};

// 发送验证码逻辑
function sendCode(type) {
  // 这里模拟发送验证码的逻辑
  isDisabledOfPw.value = true;
  buttonTextOfPw.value = '验证码已发送';

  // 模拟验证码发送后的倒计时
  setTimeout(() => {
    isDisabledOfPw.value = false;
    buttonTextOfPw.value = '重新发送验证码';
    pwCodeSuccess.value = true;  // 模拟验证码验证成功
  }, 3000); // 3秒后可以重新发送
}

// 更新密码
function updatePassword() {
  if (PWform.value.password === PWform.value.confirmPassword && PWform.value.password.length >= 6 && pwCodeSuccess.value) {
    const encryptedPw = md5(PWform.value.password);  // 使用 md5 加密密码
    axios.post('/api/changePassword', { password: encryptedPw }).then(res => {
      if (res.data === 200) {
        alert('密码修改成功');
        dialogVisible_pw.value = false;
      }
    }).catch(err => {
      alert('密码修改失败，请重试');
    });
  }
}

// 退出密码修改
function exitUpdatePassword() {
  PWform.value.password = "";
  PWform.value.confirmPassword = "";
  pwCode.value = "";
  dialogVisible_pw.value = false;
}
const PWform = reactive({
  password: "",
  confirmPassword: ""
});

const genderOptions = [
  { value: "无性别", label: "无性别" },
  { value: "男", label: "男" },
  { value: "女", label: "女" }
];

// 加载用户信息
onMounted(() => {
  loadUserInfo();
});

function loadUserInfo() {
  axios.get('/api/users/'+ my_id ).then(res => {
    if (res.data.code === 200) {
      const data = res.data.data;
      Object.assign(userInfo, {
        user_name: data.username,
        bio: data.bio || "",
        birthday: data.birthday || "",
        gender: data.gender || "无性别",
        avatar: data.profilePicture,
        bgcover: data.backgroundPicture
      });
      Object.assign(cache, userInfo);
    }
  });
}

function editUserInfo() {
  const payload = {
    id: my_id,
    name: userInfo.user_name,
    bio: userInfo.bio,
    gender: userInfo.gender,
    birthday: userInfo.birthday
  };
  console.log(payload);
  
  axios.post('/api/users/updateInfo', payload).then(res => {
    if (res.data.code === 200) {
      isReadonly.value = true;
      info.value = "修改成功";
      infoVisible.value = true;
      Object.assign(cache, userInfo);
    } else {
      info.value = "修改失败";
      infoVisible.value = true;
    }
  });
}

function cancelEdit() {
  isReadonly.value = true;
  Object.assign(userInfo, cache);
}

function exitLogin() {
  title.value = "提示";
  info.value = "退出登录成功，三秒后跳转到登录页面";
  user.loginstatus = false;
  user.userInfo = {};
  infoVisible.value = true;
  setTimeout(() => {
    window.location.href = "./login";
  }, 3000);
}

async function  ImgUpload(file:File,type:string) {
  console.log(file);
  
  try {
    const formData = new FormData();
    formData.append('file', file);

      const response = await axios.post(`/file/upload/file`, formData, {
        headers: {
      'Content-Type': 'multipart/form-data',

    },
      });
      console.log('Response:', response);
      if(type === 'avatar'){
        Object.assign(userInfo, {
        avatar: response.data.path,
      });
      }else if(type === 'bgcover'){
        Object.assign(userInfo, {
        bgcover: response.data.path,
      });
      }
      

      ElMessage({
        message: '图片上传成功',
        type: 'success',
      });
      axios.post('/api/users/updateImg', {
        id: my_id,
        profilePicture:userInfo.avatar,
        backgroundPicture: userInfo.bgcover
      }).then(res => {
        console.log(res);
      })
      
    } catch (error) {
      ElMessage({
        message: '图片上传失败，请重试',
        type: 'error',
      });
      console.error('Error uploading image:', error);
    }
}

function bgcoverUpload(file) {
  uploadImage(file, 'bgcover', (url) => {
    userInfo.bgcover = url;
    info.value = "背景修改成功";
    infoVisible.value = true;
  });
}

function uploadImage(file, type, callback) {
  const isJPG = file.type === "image/jpeg";
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG || !isLt2M) {
    info.value = isJPG ? "图片大小不能超过 2MB!" : "图片只能是 JPG 格式!";
    infoVisible.value = true;
    return;
  }
  const imagePath = `${type}/${my_id}/${Math.random().toString(36).slice(-10)}.jpg`;
  put(imagePath, file).then(it => {
    callback(it.url);
  });
}



// 手机号相关逻辑
const formattedPhoneNumber = computed(() => {
  if (phoneNumber.value.length < 7) {
    return phoneNumber.value;
  }
  const prefix = phoneNumber.value.slice(0, 3);
  const suffix = phoneNumber.value.slice(-4);
  const stars = '*'.repeat(phoneNumber.value.length - 7);
  return `${prefix}${stars}${suffix}`;
});






</script>
<style scoped>
/* 页面布局 */
.page-container {
  display: flex;
  justify-content: center;
  /* align-items: center; */
  min-height: 80vh;
  /* 保证页面在垂直方向上居中 */
  background-color: var(--roleHeaderBgColor);
}

.main-body {
  display: flex;
  /* justify-content: center; */
  background-color: var(--bPageBgColor);
  width: 800px;
  height: 600px;
}

/* 侧边栏 */
.sidebar {
  width: 100px;
  padding: 20px;
  background-color: var(--bPageBgColor);
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.tabs {
  display: flex;
  flex-direction: column;
}


.tab_title {
  padding: 12px;
  font-size: 19px;
  color: var(--selectRowBgColor);
  text-align: center;
}

.tab_item {
  padding: 12px;
  font-size: 18px;
  color: var(--bTextColor);
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  text-align: center;
  margin: 10px 0;
}

.tab_item:hover {
  background-color: rgba(0, 0, 0, 0.2);
  color: var(--selectRowBgColor);
}

.tab_item.active {
  background-color:  var(--bHoverColor);
  color: var(--selectRowBgColor);
}

.logout {
  color: #d9534f;
  font-weight: bold;
  position: relative;

}

.content {
  flex: 1;
  background-color: var(--bPageBgColor);
  border-radius: 10px;
  min-width: 400px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 信息表单 */
.user-info-form {
  max-width: 500px;
}

.info-section {
  text-align: center;
}

.btn-cancel {
  background-color: #d9534f;
  color:  var(--bTextColor);
  margin-right: 10px;
}

.btn-save {
  background-color: #5cb85c;
  color:  var(--bTextColor);
}

/* 头像与背景上传部分 */
.avatar-section {
  text-align: center;
}

.upload-area {
  display: flex;
  justify-content: space-around;
}

.avatar-uploader {
  position: relative;
  width: 220px;
  height: 220px;
  margin-bottom: 15px;
  border: 2px solid #409eff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.avatar-uploader:hover {
  border-color:  var(--bHoverColor);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}

.overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  background: rgba(0, 0, 0, 0.5);
  transition: background 0.3s ease;
}

.overlay:hover {
  background: rgba(0, 0, 0, 0.7);
}

.text {
  position: absolute;
  left: 36%;
  bottom: 30%;
  text-align: center;
  color:  var(--bTextColor);
}


/* 账号安全 */
.security-section {
  max-width: 500px;
}


.security-section {
  max-width: 500px;
  margin: auto;
}



.send-b {
  background-color: #5cb85c;
  color:  var(--bTextColor);
}

.exit-b {
  background-color: #d9534f;
  color:  var(--bTextColor);
}
</style>